package com.xiaode.controller.app.teacher.example;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Redis;
import com.xiaode.common.SysInit;
import com.xiaode.common.constant.Const;
import com.xiaode.common.model.*;
import com.xiaode.common.model.dto.notice.NoticeDTO;
import com.xiaode.exce.EnumError;
import com.xiaode.util.ChatUtil;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

public class ExampleService {

    /**
     * 需要审核的重要他人
     *
     * @param teacherId 教师id
     * @param page
     * @param limit
     * @param state     状态
     * @param keyWord   关键字
     * @return
     * @throws Exception
     */
    public Ret needExamineExample(Integer teacherId, Integer page, Integer limit, Integer state, String keyWord) throws Exception {
        if (keyWord != null) {
            keyWord = keyWord.trim();
        }
        Kv kv = Kv.by("teacherId", teacherId).setIfNotNull("state", state).setIfNotNull("keyWord", keyWord);
        List<Record> list = Db.template("findExampleStuInfo", kv).find();
        for (int i = 0; i < list.size(); i++) {
            Record record = list.get(i);
            Integer id = record.getInt("id");
            Example example = Example.dao.findFirst("SELECT * FROM `example` WHERE studentId = ? AND isDele = 0", id);
            record.put("example", example);
        }
        return Ret.ok("records", list);
    }

    /**
     * 审核榜样
     *
     * @param admin
     * @param exampleId     榜样id
     * @param state         状态
     * @param examineReason 原因
     * @return
     * @throws Exception
     */
    @Before(Tx.class)
    public Ret examineExample(Admin admin, Integer exampleId, Integer state, String examineReason) throws Exception {
        Integer teacherId = admin.getId();
        Example example = Example.dao.findFirst("SELECT * FROM example WHERE id = ? AND isDele = 0", exampleId);
        if (BeanUtil.isEmpty(example)) {
            return Ret.fail().set("error", EnumError.EXAMPLE_NULL.getObj());
        }
        TeacherStudent teacherStudents = TeacherStudent.dao.findFirst("SELECT * FROM teacher_student WHERE teacherId = ? AND studentId = ? AND state = 2", teacherId, example.getStudentId());
        if (BeanUtil.isEmpty(teacherStudents)){
            return Ret.fail().set("error",EnumError.NOT_USER_STUDENT.getObj());
        }
        example.setState(state);
        example.setUpdateTime(LocalDateTime.now());
        example.setTeacherId(teacherId);
        example.setExamineReason(examineReason);

        AtomicReference<Integer> sumState = new AtomicReference<>(state);
//        List<StudentExampleTask> exampleTasks = StudentExampleTask.dao.find("SELECT * FROM student_example_task WHERE studentId = ?",example.getStudentId());
//        if (ObjectUtil.isAllNotEmpty(exampleTasks)) {
//            exampleTasks.stream().forEach(studentExampleTask -> {
//                sumState.set(SysInit.getSumState(sumState.get(), studentExampleTask.getState()));
//            });
//        }
        example.setSumState(sumState.get());
        example.update();
        //发送通知给学生
        if (state == 3) {
            NoticeDTO noticeDTO = new NoticeDTO();
            noticeDTO.setName(admin.getName());
            noticeDTO.setPic(admin.getAvatarUrl());
            noticeDTO.setAccountId(admin.getAccountId());
            noticeDTO.setType(5);
            ArrayList<Integer> list = new ArrayList<>();
            Student o = Redis.use().get(Const.user.Student + example.getStudentId());
            list.add(o.getAccountId());
            try {
                ChatUtil.sendNotice(JSONUtil.toJsonStr(noticeDTO), 1, list);
            } catch (Exception e) {

            }
        }

        return Ret.ok();
    }

    /**
     * 查询榜样列表
     */
    public Ret examplePage(Integer page, Integer limit, Integer state, String keyWord) throws Exception {
        Kv kv = Kv.create().setIfNotNull("state", state).setIfNotNull("keyWord", keyWord);
        Page<Record> findExamkplePage = Db.template("findExamkplePage", kv).paginate(page, limit);
        return Ret.ok("examplePage", findExamkplePage);
    }

//    //老师下学生的榜样任务
//    public Ret exampleTaskPage(Integer teacherId, Integer page, Integer limit) throws Exception {
//        //获取老师绑定的学生
//        Page<TeacherStudent> tsPage = TeacherStudent.dao.paginate(page, limit, "SELECT studentId ", "FROM teacher_student WHERE teacherId = ? AND state = 2", teacherId);
//        //获取学生的榜样
//        for (TeacherStudent ts : tsPage.getList()) {
//            //学生信息
//            Student s = Student.dao.findFirst("SELECT number,avatarUrl,name FROM student WHERE id = ? ", ts.getStudentId());
//            ts.put(s);
//            //榜样信息
//            List<ExampleStudent> esList = ExampleStudent.dao.find("SELECT e.pictureUrl,e.name,es.exampleId FROM example_student es INNER JOIN example e ON es.exampleId = e.id WHERE es.studentId = ?", ts.getStudentId());
//            ts.put("esList", esList);
//            //榜样任务
//            List<StudentExampleTask> setList = StudentExampleTask.dao.find("SELECT * FROM student_example_task WHERE studentId = ? ORDER BY state", ts.getStudentId());
//            ts.put("setList", setList);
//        }
//        return Ret.ok("tsPage", tsPage);
//    }

    /**
     * 审核榜样任务
     */
    @Before(Tx.class)
    public Ret examineTask(Integer teacherId, Integer setId, Integer state, String reason) throws Exception {
        StudentExampleTask seTask = StudentExampleTask.dao.findById(setId);
        if (BeanUtil.isEmpty(seTask)) {
            return Ret.fail().set("error", EnumError.EXAMPLE_TASK_NULL.getObj());
        }
        TeacherStudent ts = TeacherStudent.dao.findFirst("SELECT * FROM teacher_student WHERE teacherId = ? AND studentId = ? AND state = 2", teacherId, seTask.getStudentId());
        if (BeanUtil.isEmpty(ts)) {
            return Ret.fail().set("error", EnumError.NOT_USER_STUDENT.getObj());
        }
        //保存榜样任务修改
        seTask.setState(state);
        seTask.setUpdateTime(LocalDateTime.now());
        seTask.setTeacherId(teacherId);
        seTask.setReason(reason);
        seTask.update();
        //查询学生的榜样
        Example example = Example.dao.findFirst("SELECT * FROM example WHERE studentId = ? AND isDele = 0",seTask.getStudentId());

//        更改总体状态
        AtomicReference<Integer> sumState = new AtomicReference<>(example.getState());
        
        List<StudentExampleTask> exampleTasks = StudentExampleTask.dao.find("SELECT * FROM student_example_task WHERE id != ? AND studentId = ?", setId, example.getStudentId());
        if (ObjectUtil.isAllNotEmpty(exampleTasks)) {
            exampleTasks.stream().forEach(studentExampleTask -> {
                sumState.set(SysInit.getSumState(sumState.get(), studentExampleTask.getState()));
            });
        }
        sumState.set(SysInit.getSumState(sumState.get(),state));
        example.setSumState(sumState.get());
        example.update();
        
        return Ret.ok();
    }

//    public Ret delExamplApply(Integer teacherId, Integer exId, String reason) {
//        DelExamplApply dea = DelExamplApply.dao.findFirst("SELECT * FROM del_exampl_apply WHERE exampleId = ? AND teacherId = ?", exId, teacherId);
//        if (BeanUtil.isEmpty(dea)) {
//            dea = new DelExamplApply();
//            dea.setExampleId(exId);
//            dea.setTeacherId(teacherId);
//            dea.setAddTime(LocalDateTime.now());
//            if (StrUtil.isNotBlank(reason)) {
//                dea.setReason(reason);
//            }
//            dea.save();
//        } else {
//            dea.setAddTime(LocalDateTime.now());
//            if (StrUtil.isNotBlank(reason)) {
//                dea.setReason(reason);
//            }
//            dea.update();
//        }
//        return Ret.ok();
//    }

    /**
     * 榜样详情页面
     *
     * @param adminId
     * @param studentId
     * @return
     */
    public Ret exampleDetailPage(Integer adminId, Integer studentId) {
        TeacherStudent first = TeacherStudent.dao.findFirst("SELECT * FROM teacher_student WHERE teacherId = ? AND studentId = ? AND state = 2", adminId, studentId);
        if (BeanUtil.isEmpty(first)) {
            return Ret.fail().set("error", EnumError.NOT_USER_STUDENT.getObj());
        }

        Example examples = Example.dao.findFirst("SELECT * FROM example where studentId = ? AND isDele = 0 ORDER BY `addTime` desc", studentId);
        Record example = new Record();
        if (BeanUtil.isNotEmpty(examples)) {
            example = examples.toRecord();
            Integer count = Db.queryInt("SELECT COUNT(*) FROM example WHERE name = ? AND isDele = 0", example.getStr("name"));
            example.put("count", count);
        } else {
            example.put("count", 0);
        }
        List<StudentExampleTask> studentExampleTasks = StudentExampleTask.dao.find("SELECT * FROM student_example_task WHERE studentId = ?", studentId);
        example.put("tasks", studentExampleTasks);
        return Ret.ok("exampleDetails", example);
    }
}
